package com.cdu.service.Impl;

import com.cdu.commons.MallConstants;
import com.cdu.commons.ServiceCode;
import com.cdu.commons.ServiceException;
import com.cdu.mapper.UserMapper;
import com.cdu.pojo.entity.Address;
import com.cdu.pojo.vo.UserInfoVO;
import com.cdu.pojo.vo.UserLoginVO;
import com.cdu.pojo.dto.TokenUser;
import com.cdu.pojo.dto.UserLoginDTO;
import com.cdu.pojo.dto.UserRegDTO;
import com.cdu.pojo.entity.User;
import com.cdu.service.UserService;
import com.cdu.util.AliOSSUtils;
import com.cdu.util.JwtUtils;
import com.cdu.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AliOSSUtils aliOSSUtils;

    //用户注册的业务层
    @Override
    public void reg(UserRegDTO userRegDTO) {
        //用户密码不一致校验
        if (!userRegDTO.getPassword().equals(userRegDTO.getRePassword())) {
            throw new ServiceException("确认密码与密码不一致", ServiceCode.DATA_CHECK_ERROR);
        }

        String salt = UUID.randomUUID().toString().replace("-", "");
        //使用盐值+密码+散列次数进行加密
        String password = MD5Utils.enctype(userRegDTO.getPassword(), salt,
                MallConstants.HASH_TIME);
        //封装用户注册的信息
        User user = new User();
        user.setUsername(userRegDTO.getUsername());
        user.setPassword(password);
        user.setSalt(salt);
        user.setIsDelete(MallConstants.IS_NOT_DELETE);// 0代表不删除，1：删除
        user.setCreatedUser(userRegDTO.getUsername());
        //将时间在数据库新增数据时进行设置
        int result = 0;
        try {
            //调用持久层新增用户信息
            result = userMapper.insert(user);
        } catch (Exception e) {
// todo 抛异常
            throw new ServiceException("注册失败:数据库错误", ServiceCode.INSERT_ERROR);
        }
        if (result != 1) {
// todo 抛异常
            throw new ServiceException("注册失败:SQL语句执行失败", ServiceCode.INSERT_ERROR);
        }
//执行成功了
    }

    //登录接口
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //在数据中查找是否这个用户信息
        User user = userMapper.getUserByUsername(userLoginDTO.getUsername());
        if (user == null) {
            throw new ServiceException("登录失败，用户名不存在", ServiceCode.DATA_CHECK_ERROR);
        }
        //用户存在，拿到盐值，加密用户密码
        String loginPassword = MD5Utils.enctype(userLoginDTO.getPassword(), user.getSalt(), MallConstants.HASH_TIME);
        //密码比对
        if (!loginPassword.equals(user.getPassword())) {
            throw new ServiceException("登陆失败，密码错误", ServiceCode.DATA_CHECK_ERROR);
        }
        //封装数据
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setId(user.getId());
        userLoginVO.setAvatar(user.getAvatar());
        userLoginVO.setUsername(user.getUsername());
        userLoginVO.setToken(JwtUtils.createToken(user.getUsername(), Long.valueOf(user.getId())));

        return userLoginVO;
    }


    //查询用户信息接口
    @Override
    public UserInfoVO getUserInfo(TokenUser tokenUser) {
        User user = userMapper.getUserByUsername(tokenUser.getUsername());
        //封装数据
        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setUsername(tokenUser.getUsername());
        userInfoVO.setPhone(user.getPhone());
        userInfoVO.setEmail(user.getEmail());
        userInfoVO.setGender(user.getGender());
        return userInfoVO;
    }

    @Override
    public String upload(MultipartFile file, TokenUser tokenUser) {
        //判断文件是否为空
        if (file == null || file.isEmpty()) {
            throw new ServiceException("上传的头像为空", ServiceCode.UPLOAD_REEOR);
        }
        //上传文件并返回url,这里利用阿里云提供的工具类,已经注册成组件了，所以先注入
        String avtorUrl;
        try {
            avtorUrl = aliOSSUtils.upload(file);
        } catch (IOException e) {
            throw new ServiceException("上传文件失败", ServiceCode.UPLOAD_REEOR);
        }
        //首先查询用户是否存在,复用接口
        User user = userMapper.getUserByUsername(tokenUser.getUsername());
        if (user == null) {
            throw new ServiceException("此用户不存在", ServiceCode.DATA_CHECK_ERROR);
        }
        //封装对象,这里可以直接设置字段
        user.setAvatar(avtorUrl);
        user.setModifiedUser(tokenUser.getUsername());
        int result = userMapper.updateAvtor(user);
        if (result != 1) {
            throw new ServiceException("数据库插入失败", ServiceCode.DATA_INSERT_ERROR);
        }

        return avtorUrl;
    }


    //修改密码业务层
    @Override
    public void updatePwd(TokenUser tokenUser, String oldPassword, String newPassword) {
        //查询用户是否存在
        User user = userMapper.getUserByUsername(tokenUser.getUsername());
        if (user == null) {
            throw new ServiceException("此用户不存在", ServiceCode.DATA_CHECK_ERROR);
        }
        //校验旧密码是否正确
        String oldPasswordMd5 = MD5Utils.enctype(oldPassword, user.getSalt(), MallConstants.HASH_TIME);
        if (!oldPasswordMd5.equals(user.getPassword())) {
            throw new ServiceException("旧密码错误", ServiceCode.DATA_CHECK_ERROR);
        }
        //新密码加密
        String newPasswordMd5 = MD5Utils.enctype(newPassword, user.getSalt(), MallConstants.HASH_TIME);
        //更新密码
        user.setPassword(newPasswordMd5);
        user.setModifiedUser(tokenUser.getUsername());
        int result = userMapper.updatePwd(user);
        if (result != 1) {
            throw new ServiceException("密码修改失败", ServiceCode.DATA_UPDATE_ERROR);
        }
    }

    //修改个人信息业务层
    @Override
    public void updateUserInfo(TokenUser tokenUser, UserInfoVO userInfoVO) {
        //查询用户是否存在
        User user = userMapper.getUserByUsername(tokenUser.getUsername());
        if (user == null) {
            throw new ServiceException("此用户不存在", ServiceCode.DATA_CHECK_ERROR);
        }
        //更新用户信息
        user.setPhone(userInfoVO.getPhone());
        user.setEmail(userInfoVO.getEmail());
        user.setGender(userInfoVO.getGender());
        user.setModifiedUser(tokenUser.getUsername());
        int result = userMapper.updateUserInfo(user);
        if (result != 1) {
            throw new ServiceException("个人信息修改失败", ServiceCode.DATA_UPDATE_ERROR);
        }
    }


    /**
     *
     * @param tokenUser
     * @return
     */

    @Override
    public List<Address> getUserAddress(TokenUser tokenUser) {
        //查询用户是否存在
        User user = userMapper.getUserByUsername(tokenUser.getUsername());
        if (user == null) {
            throw new ServiceException("此用户不存在", ServiceCode.DATA_CHECK_ERROR);
        }
        //查询用户地址
        List<Address> addressList = userMapper.getUserAddress(user.getId());
        if (addressList == null || addressList.size() == 0) {
            return null;
        }
        return addressList;
    }

}
